import { useInitialState } from '@/hooks/use-initial-state'
import { logout } from '@/store/actions/login'
import {
  getUserProfile,
  updateUserPhoto,
  updateUserProfile
} from '@/store/actions/profile'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog
} from 'antd-mobile'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { ChangeEvent, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import EditInput from '../EditInput'
import EditList from '../EditList'

import styles from './index.module.scss'

type EditPopupState = {
  visible: boolean
  type: '' | 'name' | 'intro'
}

type EditListPopupState = {
  visible: boolean
  type: '' | 'gender' | 'photo'
}

const Item = List.Item

const ProfileEdit = () => {
  const history = useHistory()

  const dispatch = useDispatch()

  // 控制弹层修改昵称和简介
  const [editPopup, setEditPopup] = useState<EditPopupState>({
    visible: false,
    type: ''
  })

  // 控制弹层修改性别和头像
  const [editListPopup, setEditListPopup] = useState<EditListPopupState>({
    visible: false,
    type: ''
  })

  // 解析个人详情状态
  const { userProfile } = useInitialState(getUserProfile).profile

  // 头像文件输入
  const fileRef = useRef<HTMLInputElement>(null)

  const [showBirthdayPicker, setShowBirthdayPicker] = useState(false)
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
          onBack={() => {
            history.push('/home/profile')
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => setEditListPopup({ visible: true, type: 'photo' })}
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() => {
                setEditPopup({ visible: true, type: 'name' })
              }}
            >
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span
                  className={classNames('intro', userProfile.intro && 'normal')}
                >
                  {userProfile.intro || '未填写'}
                </span>
              }
              onClick={() => {
                setEditPopup({ visible: true, type: 'intro' })
              }}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={userProfile.gender === 1 ? '男' : '女'}
              onClick={() =>
                setEditListPopup({ visible: true, type: 'gender' })
              }
            >
              性别
            </Item>
            <Item
              arrow
              extra={userProfile.birthday}
              onClick={() => setShowBirthdayPicker(true)}
            >
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthdayPicker}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onCancel={() => setShowBirthdayPicker(false)}
            onConfirm={async (value) => {
              const birthday = dayjs(value).format('YYYY-MM-DD')
              await dispatch(updateUserProfile({ birthday }))

              Toast.show({
                content: '修改成功',
                icon: 'success'
              })

              setShowBirthdayPicker(false)
            }}
          />
        </div>

        <div className="logout">
          <Button
            className="btn"
            onClick={() => {
              Dialog.show({
                title: '温馨提示',
                content: '你确定现在要退出吗？',
                closeOnAction: true,
                // 弹窗操作按钮配置
                actions: [
                  [
                    {
                      key: 'cancel',
                      text: '取消',
                      style: {
                        color: 'blue'
                      }
                    },
                    {
                      key: 'confirm',
                      text: '确定',
                      danger: true,
                      bold: true,
                      onClick: () => {
                        dispatch(logout())
                        history.push('/login')
                        Toast.show({
                          content: '退出成功',
                          icon: 'success'
                        })
                      }
                    }
                  ]
                ]
              })
            }}
          >
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改昵称和简介的弹出层  */}
      <Popup
        destroyOnClose
        visible={editPopup.visible}
        position="right"
        bodyStyle={{ height: '100%' }}
      >
        <EditInput
          type={editPopup.type}
          onClose={() => {
            setEditPopup({ visible: false, type: '' })
          }}
          onUpdate={async (type: string, value: string) => {
            // console.log(type, value)
            await dispatch(updateUserProfile({ [type]: value }))

            Toast.show({
              content: '修改成功',
              icon: 'success'
            })

            setEditPopup({ visible: false, type: '' })
          }}
        />
      </Popup>

      {/* 修改头像和性别得弹出层 */}
      <Popup visible={editListPopup.visible} position="bottom" destroyOnClose>
        <EditList
          onClose={() => {
            setEditListPopup({ visible: false, type: '' })
          }}
          type={editListPopup.type}
          onUpdate={async (type: string, value: string) => {
            // console.log(type, value)
            if (type === 'photo') {
              return fileRef.current?.click()
            }
            await dispatch(updateUserProfile({ [type]: value }))

            Toast.show({
              content: '修改成功',
              icon: 'success'
            })

            setEditListPopup({ visible: false, type: '' })
          }}
        />
      </Popup>

      {/* 头像输入 */}
      <input
        type="file"
        hidden
        ref={fileRef}
        onChange={async (e: ChangeEvent<HTMLInputElement>) => {
          const file = e.target.files![0]
          const formData = new FormData()

          formData.append('photo', file)

          await dispatch(updateUserPhoto(formData))

          Toast.show({
            content: '修改成功',
            icon: 'success'
          })

          setEditListPopup({ visible: false, type: '' })
        }}
      />
    </div>
  )
}

export default ProfileEdit
